<?php

	/**
	 * Workspace@ Engine application comment!
	 * 
	 * LICENSE
	 * This application is licensed under New BSD license.
	 * Please read complete LICENSE.txt inside of root folder for more details.
	 * 
	 * We wish you good building :) 
	 * 
	 * @category   Application
	 * @package    Bootstrap
	 * @author     Nevio Vesic <nevio@workspaceat.com>
	 * @copyright  2008-2009 Workspace@ group in association with Design strategist
	 */

	class Engine_Plugins_Users extends Engine_Application_Abstract
	{
		
		protected $db = null;
		
		protected static $user = null;
		
		function __construct()
		{

			$this->db = $this->databaseInstance();
		}
		
		public function login()
		{
			$lang = self::$plugins->language;
		    if (!isset($_SERVER['PHP_AUTH_USER'])) {
		        header("WWW-Authenticate: Basic realm=\"{$lang -> title}\"");
		        header("HTTP/1.0 401 Unauthorized");
		        print "Sorry - you need valid credentials to be granted access!\n";
		        exit;
		    } else {
		        if (($_SERVER['PHP_AUTH_USER']) && ($_SERVER['PHP_AUTH_PW'])) {
							
							$user = $_SERVER['PHP_AUTH_USER'];
							$password = base64_encode( md5( $_SERVER['PHP_AUTH_PW'] ) );	
							
							$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
							
							$record = $this->db -> fetchRow ( 
									"SELECT username, id FROM users WHERE
									 username = '{$user}' AND password = '{$password}' 
									 AND banned = 'false' " 
							);
							
							if ( !$this->isAuthenticated() )
							{
								
							}
							if ( $record -> id )
							{
								if ( self::$user )
								{
									self::$user = null;
								}
								
								self::$user = new Zend_Session_Namespace( "Workspace_Backend_User" );
								self::$user -> id = $record -> id;
								self::$user -> username = $record -> username;
								self::$user -> ip = $_SERVER['REMOTE_ADDR'];
								
							}
							else 
							{
								$_SERVER['PHP_AUTH_PW'] = false;
								$_SERVER['PHP_AUTH_USER']  = false;
								self::$user = null;
							}	
		            
		        } else {
		            header("WWW-Authenticate: Basic realm=\"{$lang -> title}\"");
		            header("HTTP/1.0 401 Unauthorized");
		            print "Bad credentials...\n";
		            exit;
		        }
		    }			
		}
		
		public function isAuthenticated()
		{
			if ( self::$user == null )
				return false;
				
			return true;
		}
		
		public function logout()
		{
			$_SERVER['PHP_AUTH_PW'] = false;
			$_SERVER['PHP_AUTH_USER']  = false;
			Zend_Session_Namespace::unlock();
			Zend_Session_Namespace::unsetAll();
			self::$user -> username = false;
			self::$user = null;
			Zend_Session::namespaceUnset("Workspace_Backend_User");
			#$this->login();
		}
		
		
	}

